package com.wdl.fm.core.shiro;

import com.wdl.fm.common.exception.LoginException;
import com.wdl.fm.common.model.SysPermission;
import com.wdl.fm.common.model.SysRole;
import com.wdl.fm.common.model.SysUser;
import com.wdl.fm.system.user.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 用户身份验证,授权 Realm 组件
 *
 * @author StarZou
 * @since 2014年6月11日 上午11:35:28
 **/
@Component(value = "securityRealm")
public class SecurityRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 权限检查
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        String username = String.valueOf(principals.getPrimaryPrincipal());

        SysUser user = userService.getUserByName(username);
        List<SysRole> rolesByUserID = userService.getRolesByUserID(user.getId(),username);
        for (SysRole role:rolesByUserID){
            authorizationInfo.addRole(role.getRolename());
        }

        List<SysPermission> permissionsByUserID = userService.getPermissionsByUserID(user.getId(),username);
        for (SysPermission permission:permissionsByUserID){
            authorizationInfo.addStringPermission(permission.getSign());
        }

        return authorizationInfo;
    }

    /**
     * 登录验证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = String.valueOf(token.getPrincipal());
        String password = new String((char[]) token.getCredentials());

        try {
            userService.authenticationUser(username, password);
        } catch (LoginException e) {
            throw new AuthenticationException(e.getMessage());
        }

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, getName());



        return authenticationInfo;
    }

}
